// TID Sozlugu JavaScript Document

/*** Internet Connectivity ***/
var monitor; 
var internetConnection = true;
function testHTTP() { 
	monitor = new air.URLMonitor(new air.URLRequest('http://www.adobe.com')); 
	monitor.addEventListener(air.StatusEvent.STATUS, announceStatus); 
	monitor.start(); 
}
function announceStatus(e) { 
	if(monitor.available)
		internetConnection = true;
	else
		internetConnection = false; 
}

var watchedItemColor = "#AA3300";
var operatingSystemOK = false;

/*** Video Player Part ***/
var netConn = new air.NetConnection()
netConn.connect(null);

var netStream = new air.NetStream(netConn);
netStream.addEventListener(air.AsyncErrorEvent.ASYNC_ERROR, asyncError);

var video = new air.Video(352,288);
var lastPlayedVideoId = 0;

function asyncError() {
}


var videoUrlPrefix = "http://www.cmpe.boun.edu.tr/tid/videos/";
var videoDirName = "TidSozlugu";
var videoDirFullPath = air.File.applicationStorageDirectory.resolvePath(videoDirName);
if ( !videoDirFullPath.exists )
	videoDirFullPath.createDirectory();

function PlayVideo() {
	var id = document.getElementById('videoItems').value;
	var videoFile = air.File.applicationStorageDirectory.resolvePath(videoDirName + air.File.separator + id + ".flv");
	if( operatingSystemOK && !videoFile.exists && internetConnection) {
		var videoUrl = videoUrlPrefix + id + ".flv";
		DownloadFile(videoUrl, videoFile, id);
		//document.getElementById('statusBox').innerHTML = 'Yükledim: ' + videoFile.nativePath;
	}
	if(id != '') {
		lastPlayedVideoId = id;
		PlayVideoAgain();
	}
}

function DisplayComponentsForVideo(visible) {
	if(visible) {
		video.visible = true;
		document.getElementById('noConnection').style.visibility = "hidden";
		document.getElementById('videoBox').style.visibility = "visible";
		document.getElementById('statusBox').style.visibility = "visible";
		document.getElementById('videoRegion').style.cursor = "pointer";
	}
	else {
		video.visible = false;
		document.getElementById('noConnection').style.visibility = "visible";
		document.getElementById('videoBox').style.visibility = "hidden";
		document.getElementById('statusBox').style.visibility = "hidden";
		document.getElementById('videoRegion').style.cursor = "default";
	}
}


function PlayVideoAgain() {
	
	var id = lastPlayedVideoId;
	var videoFile = air.File.applicationStorageDirectory.resolvePath(videoDirName + air.File.separator + id + ".flv");
	
	document.getElementById('videoBox').innerHTML = GetVideoName(id);
	if( operatingSystemOK && videoFile.exists ) {
		DisplayComponentsForVideo(true);
		netStream.play(videoFile.nativePath);
		document.getElementById('loader').style.visibility = "hidden";
	}
	else {
		if(internetConnection) {
			DisplayComponentsForVideo(true);
			netStream.play(videoUrlPrefix + id + ".flv");
			if(operatingSystemOK)
				document.getElementById('loader').style.visibility = "visible";
		}
		else {
			DisplayComponentsForVideo(false);
		}
	}
	document.getElementById('statusBox').innerHTML = 'Tekrar izlemek için videonun üstüne tıklayın.';
	//document.getElementById('statusBox').innerHTML = videoFile.nativePath;
		
}

function DownloadFile(urlString, file, id) {
	var urlReq = new air.URLRequest(urlString); 
	var urlStream = new air.URLStream(); 
	var fileData = new air.ByteArray(); 
	urlStream.addEventListener(air.Event.COMPLETE, loaded); 
	urlStream.load(urlReq); 

	function loaded(event) { 
		urlStream.readBytes(fileData, 0, urlStream.bytesAvailable); 
		writeAirFile(); 
		//PopulateVideoItems();
		document.getElementById(id).style.color = watchedItemColor;
		document.getElementById('loader').style.visibility = "hidden";
	} 
	 
	function writeAirFile() { 
		var fileStream = new air.FileStream(); 
		fileStream.open(file, air.FileMode.WRITE); 
		fileStream.writeBytes(fileData, 0, fileData.length); 
		fileStream.close();
	}
}

/*** Database Part ***/
var db = new air.SQLConnection();
function SetupDB() {
	var dbFile = air.File.applicationStorageDirectory.resolvePath("tid_sozlugu.db");
	
	var dbTemplate = air.File.applicationDirectory.resolvePath("tid_sozlugu_base.db");
	dbTemplate.copyTo(dbFile, true);	
	try {
		db.open(dbFile);
		//document.getElementById('statusBox').innerHTML = 'Connected to the database successfully.';
	}
	catch (error) {
		document.getElementById('statusBox').innerHTML = 'DB error:' + error.message + '<br />' + 'Details:' + error.details;
	}
}

/* Get name of the video from the SQL database */
function GetVideoName(id) {
	dbQuery = new air.SQLStatement();
	dbQuery.sqlConnection = db;
	dbQuery.text = "SELECT name FROM video WHERE id=" + id;
	
	try {
		dbQuery.execute();
		//document.getElementById('statusBox').innerHTML = 'DB Execution performed successfully.';
	} catch (error) {
		document.getElementById('statusBox').innerHTML = 'Error retrieving notes from DB:' + error + '<br />' + error.message;
		return;
	}
	return dbQuery.getResult().data[0].name;
}

/* Get videos from the SQL database */
function GetVideos() {
	searchedText = document.getElementById('searchBox').value;
	
	dbQuery = new air.SQLStatement();
	dbQuery.sqlConnection = db;
	dbQuery.text = "SELECT id,name FROM video WHERE name LIKE '%" + searchedText + "%' ORDER BY name";
	
	try {
		dbQuery.execute();
		//document.getElementById('statusBox').innerHTML = 'DB Execution performed successfully.';
	} catch (error) {
		document.getElementById('statusBox').innerHTML = 'Error retrieving notes from DB:' + error + '<br />' + error.message;
		return;
	}
	return dbQuery.getResult();
}

/* Get categories from the SQL database */
function GetCategories() {
	dbQuery = new air.SQLStatement();
	dbQuery.sqlConnection = db;
	dbQuery.text = "SELECT id,name FROM category";

	try {
		dbQuery.execute();
		//document.getElementById('statusBox').innerHTML = 'DB Execution performed successfully.';
	} catch (error) {
		document.getElementById('statusBox').innerHTML = 'Error retrieving notes from DB:' + error + '<br />' + error.message;
		return;
	}
	return dbQuery.getResult();
}

function IsInCategory(videoId, categoryId) {
	if(categoryId == 0) // All categories
		return true;
	else {
		var dbQuery = new air.SQLStatement();
		dbQuery.sqlConnection = db;
		dbQuery.text = "SELECT category_id FROM videocategory WHERE video_id=" + videoId + " AND category_id=" + categoryId;
		
		try {
			dbQuery.execute();
		} catch (error) {
			document.getElementById('statusBox').innerHTML = 'Error retrieving notes from DB:' + error + '<br />' + error.message;
			return;
		}
		
		result = dbQuery.getResult();
		if(!result.data) 
			return false;
		else 
			return true;
	}
}

/* Populate video items as an HTML SelectBox */
function PopulateVideoItems() {
	var selectedCategory = document.getElementById('categoryItems').value;	
	var videos = GetVideos(); 
	var numRecords = videos.data.length;
	var newHTML = '';
	var videoFile;
	for (i = 0; i < numRecords; i++) {
		if(IsInCategory(videos.data[i].id,selectedCategory)) {
			videoFile = air.File.applicationStorageDirectory.resolvePath(videoDirName + air.File.separator + videos.data[i].id + ".flv");
			if( operatingSystemOK && videoFile.exists ) {
				newHTML = newHTML + '<option value="' + videos.data[i].id + '" id="' + videos.data[i].id + '" onclick="PlayVideo(\''
						 	 	  + videos.data[i].id + '\',\'' + videos.data[i].name + '\');" style="color:' +  watchedItemColor + '">' 
								  + videos.data[i].name + '</option>';
			}
			else {
				newHTML = newHTML + '<option value="' + videos.data[i].id + '" id="' + videos.data[i].id + '" onclick="PlayVideo(\''
						 	 	  + videos.data[i].id + '\',\'' + videos.data[i].name + '\');">' + videos.data[i].name + '</option>';

			}
		}
	}
	document.getElementById('videoItems').innerHTML = newHTML;
	
	// avoid overflow of the select box
	document.getElementById('videoItems').selectedIndex = 0;
	document.getElementById('videoItems').selectedIndex = -1;
}

/* Populate category items as an HTML SelectBox */
function PopulateCategoryItems() {
	var categories = GetCategories();
	var numRecords = categories.data.length;
	
	newHTML = '<option value=0 selected>Tüm dersler</option>';
	for (i = 0; i < numRecords; i++) {
		newHTML = newHTML + '<option value="' + categories.data[i].id + '">' + categories.data[i].name + '</option>';
	}
	document.getElementById('categoryItems').innerHTML = newHTML;
}

/* Initialize the view */
function Initialize(){
	var osName;
	if (navigator.appVersion.indexOf("Win")!=-1) osName="Windows";
	if (navigator.appVersion.indexOf("Mac")!=-1) osName="MacOS";
	if (navigator.appVersion.indexOf("X11")!=-1) osName="UNIX";
	if (navigator.appVersion.indexOf("Linux")!=-1) osName="Linux";
	//if (osName == "Windows" || osName == "MacOS") operatingSystemOK = true;
	if (osName == "Windows") operatingSystemOK = true;
	testHTTP();
	SetupDB();
	PopulateVideoItems();
	PopulateCategoryItems();
	
	video.attachNetStream(netStream);
	video.x = 172;
	video.y = 275;
	window.htmlLoader.stage.addChild(video);
	//netStream.play("videos/intro.flv");
	
	var bg = document.getElementById("bg");
	bg.addEventListener("mousedown",onMove,true);
	document.getElementById('statusBox').innerHTML = ' '; /* Empty status string means success */
}


/***  Window Events ***/
function onClose(){
	var closing = new air.Event(air.Event.CLOSING, true, true);
	window.nativeWindow.dispatchEvent(closing);
	if(!closing.isDefaultPrevented())
		window.close();
}

function onMinimize(){
	var minimizing = new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,
							true, true,
							window.nativeWindow.displayState,
							air.NativeWindowDisplayState.MINIMIZED);
	window.nativeWindow.dispatchEvent(minimizing);
	if(!minimizing.isDefaultPrevented())		
		nativeWindow.minimize();
}

var onMove = function(event){
	nativeWindow.startMove();
}

function aboutNavigation() {
	var url = "http://www.cmpe.boun.edu.tr/pilab/tidsozlugu"; 
	var urlReq = new air.URLRequest(url); 
	air.navigateToURL(urlReq);
}